Ext.Loader.setPath('FormFieldUtil', contextPath+'ui_tpl/FormFieldUtil.js');
Ext.Loader.setPath('Ext.ux.MultiTraitTab', contextPath+'ux/MultiTraitTab.js');
Ext.Loader.setPath('metaLoader', contextPath+'ux/metaLoader.js');
Ext.define("Ext.ux.TreeTab",{
	requires:[
		'Ext.tree.TreePanel',
		'Ext.tab.Panel',
		'Ext.data.TreeStore',
		'Ext.ux.TabCloseMenu',
		'Ext.ux.TabScrollerMenu',
		'FormFieldUtil',
		'metaLoader',
		'Ext.ux.MultiTraitTab'
	],
	extend:'Ext.container.Container',
	xtype:'treetab',
	layout:'border',
	
	initComponent:function(){
		var metaData=this.metaData,
		mainMetaId=this.mainMetaId;
		this.treeCmpId="tree"+mainMetaId;
		this.tabCmpId="tabPanel"+mainMetaId;
		var refEnumMap=this.refEnumMap=metaData.refEnumMap,
		refMetaMap=this.refMetaMap=metaData.refMetaMap;
		var mainMeta=this.mainMeta=refMetaMap[mainMetaId];
		this.attrs=mainMeta.attrs;
		this.fields=mainMeta.fields;
		
		this.buildNameFieldMap();
		
		this.requires=[];
		Ext.apply(this,this.attrs)
		this.parentIdProperty=attrs["parentIdProperty"]||"fid";
		this.initTreeConfig('west');
		this.initTabPanelConfig('center');
		this.items=[this.treeConfig,this.tabConfig];
		this.callParent();
	},
	
	buildNameFieldMap:function(){
		var me=this,nameFieldMap=this.nameFieldMap={},
		needKeyConvert=this.needKeyConvert=false,
		defaultValueMap=this.defaultValueMap={};
		Ext.iterate(this.fields,function(field,i){
			var name=field["name"];
			nameFieldMap[name]=field;
			if(Ext.isString(name)&&name.indexOf(".")>-1){
				needKeyConvert=true;
			}
			var defaultValue=field["attrs"]["defaultValue"];
			if(defaultValue){
				defaultValueMap[field["name"]]=defaultValue;
			}
		});
		this.fillDefaultValue();
	},
	
	fillDefaultValue:function(){
		var moduleIdField=this.nameFieldMap[this.moduleProperty];
		if(moduleIdField){
			var attrs=moduleIdField.attrs=moduleIdField.attrs||{};
			attrs["required"]=true;
			attrs["defaultValue"]=this.metaData["id"];
		}
	},
	
	
	initTreeTBar:function(){
		var me=this,
		
		tbar=[{
			text:"新增",
			iconCls:"fa fa-plus-circle fa-fw",
			handler:function(){
				me.showAddNodeWin();
			}
		},{
			text:"编辑",
			iconCls:"fa fa-edit",
			handler:function(){
				me.showEditNodeWin();
			}
		},{
			text:"删除",
			iconCls:"fa fa-trash-o fa-fw",
			handler:function(){
				me.doDelete();
			}
		},{
			text:"刷新",
			iconCls:"fa fa-refresh fa-fw",
			handler:function(){
				me.refreshSelectedNode();
			}
		}];
		return tbar;
		
	},
	
	refreshSelectedNode:function(){
		var me=this,tree=me.getComponent(me.treeCmpId),sels=tree.getSelection(),
		store=tree.store;
		if(sels.length==0){
			return store.reload();
		}
		var sel=sels[0],id=sel.get("id");
		me.refreshNode(id);
	},
	refreshNode:function(id){
		var me=this,tree=me.getComponent(me["treeCmpId"]),
    	store=tree.store;
    	var node = store.getNodeById(id),fid=node.raw.fid,
    	fidNode=store.getNodeById(fid);
    	store.load({node: fidNode, callback:function() {
           var fidNode = store.getNodeById(fid),cnode=store.getNodeById(id);
            tree.getSelectionModel().select(cnode, true, true);
            fidNode.expand();
            if(cnode){
            	cnode.expand();
            }
        }, scope: this});
	},
	
	reloadNode:function(id){
		var me=this,tree=me.getComponent(me["treeCmpId"]),
    	store=tree.store;
    	var node = store.getNodeById(id);
    	store.load({node: node, callback:function() {
    		node=store.getNodeById(id);
    		if(node.raw){
    			 var currentNode = store.getNodeById(node.raw.id);
    	            tree.getSelectionModel().select(node, true, true);
    	            node.expand();
    		}
        }, scope: this});
	},
	
	buildTreeModel:function(){
		var me=this;
		return new Ext.data.TreeModel({
			 clientIdProperty: 'clientId',
			 identifier: 'negative',
			 idProperty:me.idProperty,
			 parentIdPoperty:me["parentIdProperty"]
		});
		
	},
	initTreeStore:function(){
		var me=this,action=me["action"],
		treeModel=this.buildTreeModel(),
		query=attrs["action"]||{type:"rest",url:""},
		queryUrl=query["url"];

		var proxy=this.buildProxy();
		
		var store= {
			autoDestroy :true,
			autoLoad :true,
			autoSync:true,
			proxy:proxy,
			folderSort: true,
	        sorters: [{
	            property: 'seq',
	            direction: 'ASC'
	        }],
			defaultRootId:attrs["rootId"]*1,
			defaultRootText:attrs["rootText"]||me.mainMeta["text"],
			model:treeModel,
			nodeParam:me.idProperty
		};
		return store;
	},
	buildProxy:function(){
		var attrs=this.attrs,
		action=attrs["action"],
		query=this.query=this.query||action,
		create=this.create=this.create||action,
		update=this.update=this.update||action,
		destroy=this.destroy=this.destroy||action,
		api={},actionMethods={},proxy={};
		if(action&&action.type=="rest"){
			proxy["type"]="rest";
			proxy["url"]=action["url"];
			proxy["appendId"]=true;
		}else{
			proxy["type"]="ajax";
			api["create"]=create.url;
			actionMethods["create"]=create.method||"POST";
			api["query"]=query.url;
			actionMethods["query"]=query.method||"GET";
			api["destroy"]=destroy.url;
			actionMethods["destroy"]=destroy.method||"GET";
			api["update"]=update["url"];
			actionMethods["update"]=update["method"]||"POST";
			proxy["url"]=query.url||action["url"];
			proxy["api"]=api;
			proxy["appendId"]=true;
			proxy["actionMethods"]=actionMethods;
		}
		proxy["reader"]={
			type:action["format"]||"json",
			rootProperty:'children',
			typeProperty:attrs["typeProperty"]
		};
		return proxy;
	},
	
	doDelete:function(){
		var me=this,tree=me.getComponent(me.treeCmpId),sels=tree.getSelection(),store=tree.store;
		
		if(sels.length==0)return Ext.toast('请先选择要删除的项目');
		var sel=sels[0],id=sel.get("id"),node=store.getNodeById(id);
		
		Ext.Msg.confirm('警告','确定要删除吗?',function(btn){
			if(btn=="no")return;
			node.erase();  
		});
	},
	showTab:function(id,metaId,text){
		var me=this,realModel=this.refMetaMap[metaId];
		if(!realModel){
			realModel=metaLoader.getMetaById(metaId);
			realModel[metaId]=realModel;
		}
		attrs=realModel["attrs"],
		meta = attrs["meta"],
		tabs=me.getComponent(me["tabCmpId"]),
		tabId="tab"+metaId+id,
		traitMetaIds=realModel["traitMetaIds"];
		var tab=tabs.child("#"+tabId);
		if(!tab){
			if(!traitMetaIds){
				traitMetaIds=realModel["traitMetaIds"]=[];
				var flatmap=Ext.Object.flatten(meta);
				Ext.iterate(flatmap,function(k,v){
					traitMetaIds.push(v);
				});
			}
			if(traitMetaIds.length==0)return;
			tabConfig={
					title:text,
					itemId:tabId,
					xtype:"multi_trait_tab",
					globalId:id,
					traitMetaIds:traitMetaIds,
					metaData:me["metaData"]
			};
			tab=tabs.add(tabConfig);
		}
		tabs.setActiveTab(tab);
	},
	getMetaAttrs:function(metaId,key){
		var meta=this.refMetaMap[metaId];
		if(!meta)return null;
		var attrs=meta["attrs"];
		if(attrs[key]!=undefined){
			return attrs[key];
		}
	},
	initTreeConfig:function(region){
		var me=this,store=me.initTreeStore(),
		tbar=me.initTreeTBar(),
		listeners={'itemclick':function ( view, record, item, index, e, eOpts ) {
			var id=record.get(me["idProperty"]),text=record.get("text"),
			metaId=record.get(me["typeProperty"]);
			me.showTab(id,metaId,text);
		},
		'itemdblclick':function ( view, record, item, index, e, eOpts ) {
			me.showEditNodeWin();
		}};
		var treeConfig=this.treeConfig={
				region:region,
				width:330,
				height:'auto',
				checkPropagation :'both',
				itemId:me.treeCmpId,
				store:store,
				xtype:"treepanel",
				split:true,
				tbar:tbar,
				rootVisible:false,
				listeners:listeners
		};
		if(me["seqProperty"]){
			me.moveUrl=contextPath+"meta/record/move/"+me["mainMetaId"];
			treeConfig["viewConfig"]={
		        plugins: {
		            ptype: 'treeviewdragdrop',
		            containerScroll: true
		        }
		    };
			listeners["itemmove"]=function( node, oldParent, newParent, index, eOpts )  {
				var fid=newParent.raw?newParent.raw.id:newParent.id;
				var oldfid=oldParent.raw?oldParent.raw.id:oldParent.id;
				var params={id:node.raw.id,fid:fid,seq:index};
				Ext.Ajax.request({
					url:me.moveUrl,
					params:params,
					success:function(response, opts) {
						me.reloadNode(oldfid);
						if(oldParent!=newParent){
							me.reloadNode(fid);
						}
						
				     },
					failure:function(response, opts){
						me.reloadNode(oldfid);
						if(oldParent!=newParent){
							me.refreshSelectedNode();
						}
					}
				});
			}
		}
	},
	
	
	
	initTabPanelConfig:function(region){
		var me=this,config={
			itemId:me.tabCmpId,
		    xtype:"tabpanel",
			autoLoad:true,
			layout:'card',
			autoDestroy: false,
			plugins:[{
				ptype:"tabclosemenu"
			},{
				ptype:"tabscrollermenu"
			}],
		    region: region,
		    split:true,
		    items: []
		};
		this.tabConfig=config;
	},
	
	showAddNodeWin:function(){
		var me=this,moduleId=me["mainMetaId"],attrs=me["attrs"],
		idProperty=attrs["idProperty"]||"id",
		typeProperty=attrs["typeProperty"]||"meta",
		winName=this.addNodeWinName="addNodeWin"+moduleId,
		action=attrs["action"];
		var win=me.getComponent(winName);
		if(!win){
			var items=FormFieldUtil.getFormFields(me.mainMetaId,metaData);
			Ext.iterate(items,function(item,i){
				var name=item["name"];
				if(name=="rank"){
					item.value=(moduleId);
					item.hidden=true;
				}else if(name==idProperty){
					item.value=-1;
					item.hidden=true;
				}else if(name=="flag"){
					item.value=1;
				}else if(name==me["parentIdProperty"]){
					item.readOnly=true;
				}
			});
			win=new Ext.form.Panel({
				floating:true,
				title:"新增",
				bodyPadding:10,
				itemId:winName,
				url:action["url"],
				closeToolText:"关闭",
				draggable:true,
				modal:true,
				closable:true,
				scrollable:true,
				width:400,
				maxHeight:450,
				defaults:{
					xtype:"textfield",
					width:300
				},
				method:action["method"]||"PUT",
				items:items,
				buttons:[{
					text:'提交',
					formBind:true,
					handler:function(){
						 var win=this.up('form'),form = win.getForm();
				            if (form.isValid()) {
				                form.submit({
				                    success: function(form, action) {
				                    	Ext.toast("新增成功",'提示', 't');
				                    	me.refreshSelectedNode();
				                    	win.hide();
				                    	
				                    },
				                    failure: function(form, action) {
				                    	Ext.toast(action.result.msg,'提示', 't');
				                    	me.refreshSelectedNode();
				                    }
				                });
				            }	
					}
				},{
					text:'取消',
					handler:function(){
						this.up('form').hide();
					}
				}]
			});
		}
		var sels=me.getComponent(me.treeCmpId).getSelection();
		if(sels.length==0)return Ext.toast('请先选择父节点');
		var sel=sels[0],form=win.getForm(),pfield=form.findField(me.parentIdProperty);
		pfield&&pfield.setValue(sel.get(me.idProperty));
		if(me.seqProperty){
			var seqField=form.findField(me.seqProperty);
			if(sel.data&&sel.data["children"]){
				seqField&&seqField.setValue(sel.data["children"].length);
			}else{
				seqField&&seqField.setValue(0);
			}
		}
		Ext.iterate(this.defaultValueMap,function(name,v){
			var f=form.findField(name);
			f&&f.setValue(v);
		});
		win.show();
		
	},
	showEditNodeWin:function(){
		var me=this;
		var sels=me.getComponent(me.treeCmpId).getSelection();
		if(sels.length==0)return Ext.toast('请先选择父节点');
		var winName=this.editNodeWinName=this.editNodeWinName||("editNodeWin"+moduleId),
		update=me["update"],action=me["action"];
		var win=me.getComponent(winName);
		if(!win){
			var items=FormFieldUtil.getFormFields(me.mainMetaId,metaData),
			moduleId=metaData["id"],
			idProperty=me["idProperty"],
			typeProperty=me["typeProperty"];
			Ext.iterate(items,function(item,i){
				var name=item["name"];
				if(name=="rank"){
					item.value=moduleId;
					item.hidden=true;
				}
			});
			win=new Ext.form.Panel({
				floating:true,
				title:"编辑",
				bodyPadding:10,
				url:update["url"]||action["url"],
				closeToolText:"关闭",
				draggable:true,
				closable:true,
				modal:true,
				itemId:winName,
				scrollable:true,
				width:400,
				maxHeight:450,
				defaults:{
					xtype:"textfield",
					width:300
				},
				method:update["method"]||"POST",
				items:items,
				buttons:[{
					text:'提交',
					formBind:true,
					handler:function(){
						 var win=this.up('form'),form = win.getForm();
				            if (form.isValid()) {
				                form.submit({
				                    success: function(form, action) {
				                    	Ext.toast("更新成功",'提示', 't');
				                    	me.refreshSelectedNode();
				                    	win.hide();
				                    	
				                    },
				                    failure: function(form, action) {
				                    	Ext.toast(action.result.msg,'提示', 't');
				                    	me.refreshSelectedNode();
				                    }
				                });
				            }	
					}
				},{
					text:'取消',
					handler:function(){
						this.up('form').hide();
					}
				}]
			});
		}
		var rec=sels[0],data=rec.data;
		if(this.needKeyConvert&&!data.flatten){
			data["flatten"]=true;
			Ext.apply(data,Ext.Object.flatten(data));
		}
		win.getForm().loadRecord(rec);
		win.show();
	}
});